package com.itheima.interceptor;

import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
    @Slf4j
    //@Component
    public class TokenInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Object handler) throws Exception {
            log.info("进入controller方法前执行....");
            if (servletRequest.getRequestURI().endsWith("/login"))
            {
                return true;
            }
            String token = servletRequest.getHeader("Token");
            if(StringUtils.hasText(token))
            {
                try {
                    Claims claims = JwtUtils.parseJWT(token);
                    log.info("token内容：{}",claims);
                    return true;
                } catch (Exception e) {
                    log.error("解析令牌失败", e);
                }
            }
            servletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

    }